<template>
	<view>
		<cu-custom bgColor="bg-black"><block slot="content">汇率查 一转多</block></cu-custom>
		<view class="grid" :class="[colStyle == 2 ? 'col-2' : 'col-1']">
			
			<view 
				v-for="(item, index) in currencyList"
				:key="item.shorthand"
				class="exchange_rate_item flex flex-direction justify-center padding-xs bg-white"
				:class="activeIndex == index ? 'active' : ''"
				:data-index="index"
				:data-item="item"
				@tap="changeBaseCurrency"
			>
				<view class="flex align-center">
					<view class="flex flex-direction align-center">
						<view class="currency_symbol bg-grey flex align-center justify-center">
							<text class="currency_type text-center text-sm text-white">{{item.shorthand}}</text>
						</view>
					</view>
					<view class="flex align-center margin-left-xs currency_input_wrap" style="flex:1">
						<input type="number" v-if="activeIndex == index && isShowBaseInput" v-model="baseValue" :focus="activeIndex == index" class="currency_input text-df text-green text-bold" :class="[colStyle == 1 ? 'text-xl' : '']" />
						<text v-else class="currency_input text-df text-green text-bold" :class="[colStyle == 1 ? 'text-xl' : '']">{{formatAmount(item.rate * baseValue)}}</text>
					</view>
				</view>
				<!-- <text class="capital_txt text-sm text-green">{{item.capital}}</text> -->
				<text class="currency_other_txt text-df text-green margin-top-sm" :class="[colStyle == 1 ? 'text-xl' : '']"><text class="text-gray">货币名：</text>{{item.name}}</text>
				<view class="currency_other flex  margin-top-xs">
					<text v-if="activeIndex != index" class="currency_other_txt basis-df text-sm text-green" :class="[colStyle == 1 ? 'text-lg' : '']">{{colStyle == 1 ? "比率：" : ""}}{{item.rate}}</text>
					<text v-if="item.updatetime" class="currency_other_txt currency_other_update basis-lg text-xs text-gray text-right" :class="[colStyle == 1 ? 'text-lg' : '']">{{item.updatetime}}</text>
					<text class="cuIcon-activity special_icon text-gray" v-if="mainMinCurrency == item.shorthand"></text>
					<text class="cuIcon-activityfill special_icon text-green" v-if="mainMaxCurrency == item.shorthand"></text>
				</view>
			</view>
			
			<view
				class="exchange_rate_item flex justify-center align-center padding-xs bg-white"
				hover-class="normal_hover"
				@tap="addBaseCurrency"
			>
				<text class="lg cuIcon-add setting_font text-center text-gray"></text>
			</view>
			
		</view>
		<view class="flex flex-direction">
			<view class="cu-capsule round cu-capsule-item" v-if="minCurrency">
				<view class='cu-tag bg-red'><text class='text-white'>最少:</text></view>
				<view class="cu-tag line-red">{{minCurrency.name}} {{formatAmount(minCurrency.rate * baseValue)}}</view>
			</view>
			<view class="cu-capsule round cu-capsule-item" v-if="maxCurrency">
				<view class='cu-tag bg-red'><text class='text-white'>最多:</text></view>
				<view class="cu-tag line-red">{{maxCurrency.name}} {{formatAmount(maxCurrency.rate * baseValue)}} {{maxCurrency.rate * baseValue >= 1000000 ? "百万富翁" : "" }}</view>
			</view>
		</view>
		<view class="text-xs text-gray text-center" style="line-height: 52upx;">数据取自网络，仅供参考</view>
		<!-- #ifdef MP-QQ -->
		<view class="ad_wrap">
			<common-ad unitId="039f6b1d4f58fa0bb8560be75f4b50d9" adType="banner" />
		</view>
		<!-- #endif -->
		
		<options-com @itemClick="otherAction" :list="[{title:'一转一',id:'onetoone'},{title:'增加货币',id:'add'}]"/>
		<addCurrency ref="addCurrency" />
	</view>
</template>

<script>
	import {requestSingle} from "../../controller/request_ctrl";
	import {initCurrency} from "../../utils/config";
	import {getStorage, setStorage} from "../../utils/storage_util";
	import {formatTime, formatFloat} from "../../utils/util";
	import optionsCom from "../../components/options.vue";
	import addCurrency from "../../components/add_currency.vue";
	import shareConfig from "../../utils/share_config";
	let isShow = false;
	let isFirstEnter = true;
	export default {
		data() {
			return {
				activeIndex:0,
				isShowBaseInput: true,
				baseValue: 100,
				currencyList:[
					// {
					// 	name: "人民币",
					// 	shorthand: "CNY",
					// 	value: 100,
					// 	rate: 1,
					// 	updatetime: formatTime(new Date())
					// }
				],
				baseCurrency: "CNY",
				colStyle:2, // 首页列数 2为二列 1为一列，默认是为二列
				mainMinCurrency: "", // 选择区转换最多货币
				mainMaxCurrency: "", // 选择区转换最多货币
				minCurrency: null, // 最小货币
				maxCurrency: null  // 最大货币
			}
		},
		components:{
			optionsCom: optionsCom,
			addCurrency: addCurrency
		},
		onLoad() {
			let self = this;
			this.eventBus.$on("dlgChange",function(res) {
				if(!isShow) {
					return;
				}
				if (res == "show") {
					self.isShowBaseInput = false;
				} else if(res == "hidden" || res == "addCurrencyHide") {
					self.isShowBaseInput = true;
					if (res == "addCurrencyHide") {
						self.updateCurrencyData();
					}
				}
				console.log("dlgChange事件收到通知了:", res);
			});
		},
		onReady() {
			if (!isFirstEnter) {
				return;
			}
			isFirstEnter = false;
			this.initMainData(() => {
				this.changeMainPage();
			});
		},
		onShareAppMessage() {
			return shareConfig();
		},
		onShow() {
			isShow = true;
			if (!isFirstEnter) {
				this.initMainData();
			}
		},
		onHide() {
			isShow = false;
		},
		
		methods: {
			
			/**
			 * 主界面初始化
			 * @param {Function} cb 回调函数
			 */
			initMainData(cb) {
				this.initColStyle();
				this.initDecimalCount();
				this.updateCurrencyData(cb);
			},
			/**
			 * 根据本地存储配置初始化首页样式
			 */
			initColStyle() {
				let homeColNum = getStorage("homeColNumForErtc");
				this.colStyle = homeColNum ? homeColNum : 2;
			},
			
			/**
			 * 根据本地存储配置初始化小数保留数
			 */
			initDecimalCount() {
				this.decimalDigitsNum = getStorage("decimalDigitsForErtc");
			},
			formatAmount(mount) {
				let count = this.decimalDigitsNum;
				if (count == "") {
					count = 2;
				}
				return formatFloat(mount, count)
			},
			changeBaseCurrency(e) {
				let {index, item} = e.currentTarget.dataset;
				this.activeIndex = index;
				this.baseCurrency = item.shorthand;
				this.updateCurrencyData();
			},
			updateCurrencyData(cb) {
				let initCurrencyData = getStorage("userCurrencyConfig");
				if (!initCurrencyData) {
					initCurrencyData = initCurrency;
					setStorage("userCurrencyConfig", initCurrency);
				}
				requestSingle(this.baseCurrency).then((res) => {
					console.log("首页数据初始化0："+this.baseCurrency, res, initCurrencyData);
					let result = res.result;
					let currencyData = result.list;
					let tempList =[];
					
					this.calculateCurrenMinMax(currencyData);
					initCurrencyData.forEach((item, index) => {
						let nowItem = currencyData[item];
						if (item == this.baseCurrency) {
							tempList[item == "CNY" ? "unshift" : "push"]({
								name: result.name,
								shorthand: result.currency,
								rate: 1,
								updatetime: formatTime(new Date())
							})
						}else if(nowItem) {
							tempList[item == "CNY" ? "unshift" : "push"]({
								name: nowItem.name,
								shorthand: item,
								updatetime: nowItem.updatetime,
								rate: nowItem.rate
							})
						}
					})
					console.log("首页数据初始化1："+this.baseCurrency, res, initCurrencyData, tempList);
					this.currencyList = [...tempList];
					this.calculateCurrenMinMaxMain(tempList);
					cb && cb();
				}).catch((err) => {
					console.log("首页初始化err:", err);
					cb && cb();
				});	
			},
			
			/**
			 * 左下角导航项传出的事件，根据id做不同操作
			 * @param {string} id
			 */
			otherAction(id) {
				console.log(id);
				if(id == "onetoone") {
					uni.switchTab({
						url:"/pages/onetoone/onetoone"
					})
				} else if (id == "add"){
					this.addBaseCurrency();
				}
			},
			
			// 添加更多货币
			addBaseCurrency() {
				this.$refs.addCurrency.showModal();
			},
			
			/**
			 * 根据用户常用功能跳转不同页面，主要是一转多或者一转一
			 */
			changeMainPage() {
				let mainUseFun = getStorage("mainUseFunForErtc");
				if (mainUseFun == "onetoone") {
					uni.switchTab({
						url:"/pages/onetoone/onetoone"
					})
				}
			},
			
			/**
			 * 计算所有货币里最大最小项
			 * @param {Object} list
			 */
			calculateCurrenMinMax(list) {
				let listArr = Object.values(list);
				listArr.sort((a, b) => {
					return a.rate - b.rate;
				});
				this.minCurrency = listArr[0];
				this.maxCurrency = listArr[listArr.length -1];
				console.log("当前最小最大货币:",this.minCurrency,this.maxCurrency);
			},
			
			/**
			 * 计算选择项里最大最小货币
			 */
			calculateCurrenMinMaxMain(list) {
				list.sort((a, b) => {
					return a.rate - b.rate;
				});
				this.mainMaxCurrency = list[list.length -1].shorthand;
				this.mainMinCurrency = list[0].shorthand;
			}
		}
	}
</script>

<style>
	.exchange_rate_item{
		/* border-bottom:1rpx solid #ccc;
		border-right:1rpx solid #ccc; */
		min-height: 208rpx;
		border:1rpx solid #ccc;
		box-shadow:0 0 10rpx inset #d8d8d8;
		border-radius: 6rpx;
		position: relative;
	}
	.special_icon{
		position: absolute;
		top:5rpx;
		right:5rpx;
	}
	.exchange_rate_item.active{
		background-color:#333333;
		border-color:#39B54A;
		box-shadow:0 0 10rpx inset #39B54A;
	}

	.exchange_rate_item.active .currency_symbol{
		box-shadow:0 0 5rpx #39B54A;
	}
	.exchange_rate_item.active .currency_symbol{
		background-color: #333;
	}
	.exchange_rate_item.active .currency_other_update{
		text-align:left;
	}
	.currency_symbol{
		width: 72rpx;
		height: 72rpx;
		border-radius: 6rpx;
	}
	.currency_input_wrap{
		height: 72rpx;
		border-bottom: 1rpx solid rgba(0,0,0,0.3);
	}
	.currency_input{
		width:100%;
		flex:0 0 auto;
		max-height: 72rpx;
		line-height: 36rpx;
		word-break: break-all;
	}
	.currency_type{
		line-height: 30rpx;
		white-space: nowrap;
	}
	.capital_txt{
		/* height: 56rpx; */
		margin-top:10rpx;
		line-height:28rpx;
		overflow:hidden;
	}
	.currency_other{
		width:100%;
	}
	.currency_other_txt{
		line-height: 36rpx;
		white-space:nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
	}
	.setting_font{
		font-size:80rpx!important;
	}
	.cu-capsule-item{
		margin:5rpx 0 0 0!important;
	}
</style>
